package com.qpl.depression.cms.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qpl.depression.cms.common.ServerResponse;
import com.qpl.depression.cms.entity.Employee;
import com.qpl.depression.cms.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Desc
 * @Date 2021/5/13 11:37
 **/
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 跳转到员工页面
     *
     * @return 员工页面
     */
    @GetMapping("employee/page")
    public String employeePage() {
        return "employeeList";
    }

    /**
     * 根据员工名模糊查询员工信息
     *
     * @param name 员工名
     * @return 查询数据
     */
    @GetMapping("employee/data")
    @ResponseBody
    public ServerResponse employeeData(String name) {
        List<Employee> employees = employeeService.list(Wrappers.<Employee>lambdaQuery().like(StringUtils.isNotBlank(name), Employee::getName, name));
        return ServerResponse.createBySuccess("success", employees);
    }

    /**
     * 新增员工信息界面
     *
     * @return 页面
     */
    @GetMapping("/employee/add")
    public String blogAdd() {
        return "employeeAddPage";
    }

    /**
     * 保存或者更新员工信息
     *
     * @param employee 员工信息
     * @return 保存或者更新结果
     */
    @PostMapping("employee/save")
    @ResponseBody
    public ServerResponse employeeSave(Employee employee) {
        return employeeService.saveOrUpdate(employee) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }

    /**
     * 根据员工id编辑员工信息
     *
     * @param id       员工id
     * @param modelMap 员工信息
     * @return 编辑结果
     */
    @GetMapping("/employee/edit")
    public String employeeEdit(Long id, ModelMap modelMap) {
        Employee employee = employeeService.getById(id);
        modelMap.addAttribute("employee", employee);
        return "employeeEditPage";
    }

    /**
     * 根据id删除员工信息
     *
     * @param id 员工id
     * @return 删除结果
     */
    @GetMapping("/employee/del")
    @ResponseBody
    public ServerResponse employeeDel(Long id) {
        return employeeService.removeById(id) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }

}
